<script lang="ts" setup>
import { getCurrentInstance, reactive, ref } from 'vue'
import { onLoad, onPageScroll, onReady } from '@dcloudio/uni-app'
import TnTag from '@tuniao/tnui-vue3-uniapp/components/tag/src/tag.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import TnActionSheet from '@tuniao/tnui-vue3-uniapp/components/action-sheet/src/action-sheet.vue'
import TnSticky from '@tuniao/tnui-vue3-uniapp/components/sticky/src/sticky.vue'
import { useUniAppSystemRectInfo } from '@tuniao/tnui-vue3-uniapp/hooks'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnTabs from '@tuniao/tnui-vue3-uniapp/components/tabs/src/tabs.vue'
import TnTabsItem from '@tuniao/tnui-vue3-uniapp/components/tabs/src/tabs-item.vue'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import type { TnActionSheetInstance } from '@tuniao/tnui-vue3-uniapp'
import PageContainer from '@/components/page-container/index.vue'
import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js'
import { useScrollTransparentNavbar } from '@/hooks'
import circles from '@/api/circles.js'
import { FILE_URL, USER_INFO } from '@/api/config.js'

const actionSheetRef = ref<TnActionSheetInstance>()
const paging = ref(null)
useZPaging(paging)
// 导航栏的高度
const navbarHeight = ref(0)
const instance = getCurrentInstance()
const { triggerElementId } = useScrollTransparentNavbar(instance)
const { navBarInfo } = useUniAppSystemRectInfo()
const state = reactive({
  userInfo: {},
  role: 'circleMaster,administrator',
  circlesId: 0,
  circleMasterUserId: 0,
  operateUserId: 0,
  currentTabIndex: 0,
  tabsData: ['管理员', '成员'],
  lists: [],
  actions: [
    { text: '移除圈子', value: '1' },
    { text: '拉黑用户', value: '2' },
  ],
})

const openActionSheet = (operateUserId: number) => {
  state.operateUserId = operateUserId
  actionSheetRef.value?.show({
    title: '管理成员',
    actions: state.actions,
    select: (index: number, value?: string | number) => {
      console.log('选项被点击', index, value)
      if (value == '1') {
        removeCirclesMember()
      } else if (value == '2') {
        circlesMemberAudit()
      } else if (value == '3') {
        removeCirclesManage()
      } else if (value == '4') {
        circlesManageAdd()
      }
      return true
    },
  })
}

const removeCirclesMember = () => {
  circles
    .circlesMemberRemove({
      circles_id: state.circlesId,
      remove_user_id: state.operateUserId,
    })
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        paging.value.reload(true)
      }
    })
    .catch((err: any) => {
      console.log(err, 'removeCirclesMember')
    })
}

const removeCirclesManage = () => {
  circles
    .circlesManageRemove({
      circles_id: state.circlesId,
      manage_user_id: state.operateUserId,
    })
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        paging.value.reload(true)
      }
    })
    .catch((err: any) => {
      console.log(err, 'removeCirclesManage')
    })
}

const circlesManageAdd = () => {
  circles
    .circlesManageAdd({
      circles_id: state.circlesId,
      manage_user_id: state.operateUserId,
    })
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        paging.value.reload(true)
      }
    })
    .catch((err: any) => {
      console.log(err, 'circlesManageAdd')
    })
}

const circlesMemberAudit = () => {
  circles
    .auditCirclesMember({
      circles_id: state.circlesId,
      audit_user_id: state.operateUserId,
      status: '3',
    })
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        paging.value.reload(true)
      }
    })
    .catch((err: any) => {
      console.log(err, 'circlesMemberAudit')
    })
}

const clickTabs = (index: number) => {
  state.currentTabIndex = index
  if (index == 0) {
    state.role = 'circleMaster,administrator'
  } else {
    state.role = 'member'
  }
  paging.value.reload(true)
}

const { init: initTransparentScroll, opacityScrollHandle } =
  useScrollTransparentNavbar(instance)

// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}

const navUserHomePage = (uId: number) => {
  tnNavPage(`/pagesA/userhome?otherUserId=${uId}`)
}

const queryList = (pageNo: number, pageSize: number) => {
  circles
    .circlesManage({
      page: pageNo,
      page_size: pageSize,
      circles_id: state.circlesId,
      role: state.role,
    })
    .then((res) => {
      paging.value.complete(res.data)
    })
    .catch((err: any) => {
      console.log(err, 'lists')
      paging.value.complete(false)
    })
}
onLoad((options) => {
  if (!options?.circlesId) {
    uni.showModal({
      title: '提示',
      content: '参数错误',
      showCancel: false,
      success: () => {
        uni.navigateBack()
      },
    })
    return
  }
  state.userInfo = uni.getStorageSync(USER_INFO)
  state.circlesId = options.circlesId
  state.circleMasterUserId = options.circleMasterUserId

  if (state.circleMasterUserId == state.userInfo.id) {
    if (state.currentTabIndex == 0) {
      state.actions.push({
        text: '取消管理',
        value: '3',
      })
    } else if (state.currentTabIndex == 1) {
      state.actions.push({
        text: '设为管理',
        value: '4',
      })
    }
  }
})
onReady(() => {
  initTransparentScroll()
})
onPageScroll((e) => {
  opacityScrollHandle(e.scrollTop)
})
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      :bottom-shadow="false"
      :placeholder="false"
      @init-finish="navbarInitFinishHandle"
    >
      圈子成员
    </TnNavbar>
    <view class="container" :style="{ paddingTop: `${navbarHeight}px` }">
      <TnSticky :id="triggerElementId" :offset-top="navBarInfo.height">
        <TnTabs
          v-model="state.currentTabIndex"
          :scroll="false"
          :bottom-shadow="false"
          bg-color="#ffffff"
        >
          <TnTabsItem
            v-for="(item, index) in state.tabsData"
            :key="index"
            :title="item"
            @click="clickTabs(index)"
          />
        </TnTabs>
      </TnSticky>
      <view class="tn-gray-disabled_border tn-border-bottom" />
      <view class="tn-mt-sm">
        <z-paging
          ref="paging"
          v-model="state.lists"
          use-page-scroll
          @query="queryList"
        >
          <view class="">
            <view
              v-for="(item, index) in state.lists"
              :key="index"
              class="tn-flex user-lists items-center"
            >
              <view class="" @click="navUserHomePage(item.user.id)">
                <view class="logo-pic">
                  <view class="logo-image">
                    <view
                      class=""
                      :style="
                        'background-image:url(' +
                        FILE_URL +
                        item.user.avatar +
                        ');width: 90rpx;height: 90rpx;background-size: cover;'
                      "
                    />
                  </view>
                </view>
              </view>
              <view class="tn-pl-sm" style="width: 60vw">
                <view class="tn-flex justify-between tn-text-ellipsis-1">
                  <view class="justify-content-item">
                    <text
                      class="tn-text-lg"
                      @click="navUserHomePage(item.user.id)"
                    >
                      {{ item.user.nickname }}
                    </text>
                    <TnTag
                      v-if="item.role == 'circleMaster'"
                      type="warning"
                      :custom-style="{
                        fontSize: '12px',
                        lineHeight: '12px',
                        borderRadius: '2px',
                        marginLeft: '5px',
                      }"
                    >
                      圈主
                    </TnTag>
                  </view>
                </view>
                <view class="tn-pt-xs tn-text-ellipsis tn-text-ellipsis-1">
                  <text class="tn-color-gray tn-text-sm">
                    加入时间：{{ item.create_time }}
                  </text>
                </view>
              </view>
              <view v-if="item.role != 'circleMaster'" style="width: 30vw">
                <view
                  class="tn-flex justify-end tn-mb-xs tn-mt-xs"
                  @click="openActionSheet(item.user.id)"
                >
                  <TnButton
                    v-if="
                      state.currentTabIndex == 0 &&
                      state.circleMasterUserId == state.userInfo.id
                    "
                    type="primary"
                    icon="align"
                    border-color="#080808"
                    text-color="#080808"
                    bg-color="#c6d1d8"
                  />
                  <TnButton
                    v-else-if="state.currentTabIndex == 1"
                    type="primary"
                    icon="align"
                    border-color="#080808"
                    text-color="#080808"
                    bg-color="#c6d1d8"
                  />
                </view>
              </view>
            </view>
          </view>
        </z-paging>
      </view>
      <TnActionSheet ref="actionSheetRef" />
      <view class="tn-tabbar-height" />
    </view>
  </PageContainer>
</template>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f7f8;

  .user-lists {
    background-color: #ffffff;
    border-radius: 18rpx;
    margin: 20rpx 30rpx;
    padding: 20rpx;
  }
}

/* 用户头像 start */
.logo-image {
  width: 90rpx;
  height: 90rpx;
  position: relative;
}

.logo-pic {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  border-radius: 50rpx;
  overflow: hidden;
}

/* 底部安全边距 start*/
.tn-tabbar-height {
  min-height: 120rpx;
  height: calc(140rpx + env(safe-area-inset-bottom));
  height: calc(140rpx + constant(safe-area-inset-bottom));
}
</style>
